﻿using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Jy123.Common.Config;
using System.Net;
using System.Drawing;



namespace Jy123.Common
{
    public class Public
    {
        /// <summary>
        /// 根目录
        /// </summary>
        public static string rootDir
        {
            get
            {
                return Jy123.Common.Config.UiConfig.RootDir;
            }
        }
        /// <summary>
        /// 读JySite.config取配置文件
        /// </summary>
        /// <param name="Target">要读取节的名</param>
        /// <returns>该节的值</returns>
        public static string GetXMLValue(string Target)
        {
            string XmlPath = HttpContext.Current.Server.MapPath("~/config/base/JySite.config");
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(XmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNode node = root.SelectSingleNode(Target);
            if (node != null)
            {
                return node.InnerXml;
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 取得用户客户端IP(穿过代理服务器取远程用户真实IP地址)
        /// </summary>
        public static string GetClientIP()
        {
            HttpContext current = HttpContext.Current;
            if (current.Request.ServerVariables["HTTP_VIA"] != null)
            {
                return current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            return current.Request.ServerVariables["REMOTE_ADDR"].ToString();
        }
        /// <summary>
        /// 取得用户ID,未验证是否合法
        /// </summary>
        /// <returns></returns>
        static public int GetUserID()
        {
            int UserID = 0;
            HttpCookie cookieToken = HttpContext.Current.Request.Cookies["SNSUserPassPort"];
            if (cookieToken == null || cookieToken["token"] == null || cookieToken["token"] == "")
                return UserID;
            string userCookie = cookieToken["token"];
            string desstr = DES.Decrypt(userCookie, SecretConfig.UserKey, SecretConfig.UserIV);
            string[] userInfo = desstr.Split(SecretConfig.UserSeparator);
            UserID = int.Parse(userInfo[0]);
            return UserID;
        }
        /// <summary>
        ///获取文件地址
        /// </summary>
        public static string URLWrite(string Dir, string Req, string ID)
        {
            string ReturnStr = string.Empty;
            string isURLWrite = Config.UiConfig.Openurl;
            if (isURLWrite == "1")
            {
                if (Dir != string.Empty)
                {
                    ReturnStr = Dir + "/" + ID;
                }
                else
                {
                    ReturnStr = "u" + ID + ".aspx";
                }
            }
            else
            {
                if (Dir != string.Empty)
                {
                    if (Dir == "index")
                    {
                        ReturnStr = "?" + Req + "=" + ID;
                    }
                    else
                    {
                        ReturnStr = Dir + ".aspx?" + Req + "=" + ID;
                    }
                }
                else
                    ReturnStr = "?" + Req + "=" + ID;
            }
            return ReturnStr;
        }
        /// <summary>
        /// 读取,添加，修改xml文件
        /// </summary>
        /// <param name="Xmlpath">Xml路径</param>
        /// <param name="Node">新的子节点名称</param>
        /// <param name="Value">新节点对应的值</param>
        /// <param name="flag">1：读取，否则为 修改或者添加</param>
        /// <returns>1：修改添加成功，为空字符串表示修改添加成功，否则是读取成功</returns>
        public static string GetXML(string Xmlpath, string Node, string Value, int flag)
        {
            try
            {
                string filepath = HttpContext.Current.Server.MapPath(Xmlpath);
                XmlDocument xmlDoc = new XmlDocument();
                if (!File.Exists(filepath))
                {
                    XmlDeclaration xn = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                    XmlElement root = xmlDoc.CreateElement("rss");
                    XmlElement root1 = xmlDoc.CreateElement("item");

                    root.AppendChild(root1);
                    xmlDoc.AppendChild(xn);
                    xmlDoc.AppendChild(root);
                    xmlDoc.Save(filepath);//本地路径名字
                }
                xmlDoc.Load(filepath);//你的xml文件
                string ReStr = string.Empty;
                XmlElement xmlObj = xmlDoc.DocumentElement;

                XmlNodeList xmlList = xmlDoc.SelectSingleNode(xmlObj.Name.ToString()).ChildNodes;

                foreach (XmlNode xmlNo in xmlList)
                {
                    if (xmlNo.NodeType != XmlNodeType.Comment)//判断是不是注释类型
                    {
                        XmlElement xe = (XmlElement)xmlNo;
                        {
                            if (xe.Name == xmlObj.FirstChild.Name)
                            {
                                XmlNodeList xmlNList = xmlObj.FirstChild.ChildNodes;

                                foreach (XmlNode xmld in xmlNList)
                                {
                                    XmlElement xe1 = (XmlElement)xmld;
                                    {
                                        if (xe1.Name == Node)
                                        {
                                            if (flag == 1)//读取值
                                            {
                                                if (xmld.InnerText != null && xmld.InnerText != "")
                                                {
                                                    ReStr = xmld.InnerText;
                                                }
                                            }
                                            else//修改值
                                            {
                                                xmld.InnerText = Value;//给节点赋值
                                                xmlDoc.Save(filepath);
                                                ReStr = Value.Trim();
                                            }
                                        }
                                    }
                                }
                                if (ReStr == string.Empty)// 添加节点
                                {
                                    XmlNode newNode;
                                    newNode = xmlDoc.CreateNode("element", Node, Value);//创建节点
                                    newNode.InnerText = Value;//给节点赋值
                                    xe.AppendChild(newNode);//把节点添加到doc
                                    xmlDoc.Save(filepath);
                                    ReStr = Value.Trim();
                                }
                            }
                        }
                    }
                }
                return ReStr;
            }
            catch
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// select控件取得选择值
        /// </summary>
        /// <param name="select">选择按钮的HTML空间名</param>
        /// <param name="str">用户数据库中的值</param>
        /// <param name="bl">是否选中值</param>
        public static void GetSelect(HtmlSelect select, string str, bool bl)
        {
            for (int i = 0; i < select.Items.Count; i++)
            {
                if (bl)
                {
                    if (str == select.Items[i].Text)
                    {
                        select.Value = select.Items[i].Value;
                        break;
                    }
                }
                else
                {
                    if (str == select.Items[i].Value)
                    {
                        select.Value = select.Items[i].Value;
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 取得与当前时间的间隔(MM月dd日 刚刚更新)
        /// </summary>
        /// <param name="time1">需要对比的时间</param>
        /// <returns></returns>
        public static string GetTimeEXPINSpan(DateTime time1)
        {
            string strTime = "";
            DateTime date1 = DateTime.Now;
            DateTime date2 = time1;
            TimeSpan dt = date1 - date2;

            // 相差天数
            int days = dt.Days;
            // 时间点相差小时数
            int hours = dt.Hours;
            // 相差总小时数
            double Minutes = dt.Minutes;
            // 相差总秒数
            int second = dt.Seconds;

            if (days == 0 && hours == 0 && Minutes == 0)
            {
                strTime = "刚刚更新";
            }
            else if (days == 0 && hours == 0)
            {
                strTime = Minutes + "分钟前";
            }
            else if (days == 0)
            {
                strTime = hours + "小时前";
            }
            else
            {
                strTime = time1.ToString("MM月dd日");
            }
            return strTime;
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path">文件路径</param>
        public static bool DelFile(string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                    return true;
                }
            }
            catch (IOException ex) { throw ex; }
            return false;
        }
        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="path">文件夹路径</param>
        public static void DelDir(string path)
        {
            try
            {
                if (Directory.Exists(path))
                {
                    Directory.Delete(path);
                }
            }
            catch (IOException ex) { throw ex; }
        }
        /// <summary>
        /// 删除照片或头像
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="_type">0为头像， 1为照片， 2头像照片</param>
        //public static void DelFile(string filename, int _type)
        //{
        //    Dictionary<string, PicConfigInfo> pci;
        //    string rootdir = rootDir;
        //    string dirroot = string.Empty;
        //    string server = "";
        //    switch (_type)
        //    {
        //        case 0:
        //            pci = PicConfig.Portrait;
        //            dirroot = PicConfig.ProtraitRoot;
        //            server = PicConfig.ProtraitServer;
        //            break;
        //        case 1:
        //            pci = PicConfig.Photo;
        //            dirroot = PicConfig.PhotoRoot;
        //            server = PicConfig.PhotoServer;
        //            break;
        //        case 2:
        //            pci = PicConfig.GroupHead;
        //            dirroot = PicConfig.GroupDir;
        //            server = PicConfig.GroupServer;
        //            break;
        //        default:
        //            pci = PicConfig.Photo;
        //            dirroot = PicConfig.PhotoRoot;
        //            server = PicConfig.PhotoServer;
        //            break;
        //    }
        //    string dir;
        //    string cPath;
        //    foreach (string k in pci.Keys)
        //    {
        //        if (k != "")
        //        {
        //            dir = rootdir + "/" + pci[k].Directory;
        //            cPath = HttpContext.Current.Server.MapPath(dir) + @"\" + filename;
        //            if (string.IsNullOrEmpty(server) || server == "~")
        //            {
        //                DelFile(cPath);
        //            }
        //            else
        //            {
        //                JuSNS.Common.WebService.UploadService upsrv = new JuSNS.Common.WebService.UploadService();
        //                JuSNS.Common.WebService.MySoapHeader soapheader = new JuSNS.Common.WebService.MySoapHeader();
        //                soapheader.Password = PicConfig.SoapPass;
        //                upsrv.MySoapHeaderValue = soapheader;
        //                upsrv.DeleteFile(dir + "/" + filename);
        //            }
        //        }
        //    }
        //    dir = rootdir + "/" + dirroot;
        //    cPath = HttpContext.Current.Server.MapPath(dir) + @"\" + filename;
        //    if (string.IsNullOrEmpty(server) || server == "~")
        //    {
        //        DelFile(cPath);
        //    }
        //    else
        //    {
        //        JuSNS.Common.WebService.UploadService upsrv = new JuSNS.Common.WebService.UploadService();
        //        JuSNS.Common.WebService.MySoapHeader soapheader = new JuSNS.Common.WebService.MySoapHeader();
        //        soapheader.Password = PicConfig.SoapPass;
        //        upsrv.MySoapHeaderValue = soapheader;
        //        upsrv.DeleteFile(dir + "/" + filename);
        //    }
        //}

        
    }
}
